package org.spamforces.web.page;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.nocturne.main.Page;
import org.spamforces.model.User;

import java.io.*;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * @author MikeMirzayanov (mirzayanovmr@gmail.com)
 */
public abstract class ApplicationPage extends Page {
    protected static final String AUTHORIZED_USER_SESSION_KEY = "authorizedUser";

    private static final Gson gson = new Gson();

    @Override
    public PrintWriter getWriter() {
        try {
            return new PrintWriter(
                    new OutputStreamWriter(getOutputStream(), "UTF-8")
            );
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }

    protected User getUser() {
        return getSession(AUTHORIZED_USER_SESSION_KEY, User.class);
    }

    protected boolean isUserAuthorized() {
        return getUser() != null;
    }

    public boolean isAnonymousAccessAllowed() {
        return false;
    }

    public void printJson(Map<String, String> parameters) {
        synchronized (gson) {
            Type mapType = new TypeToken<Map<String, String>>() {
            }.getType();

            getResponse().setContentType("application/json");
            Writer writer = getWriter();

            try {
                writer.write(gson.toJson(parameters, mapType));
                writer.flush();
            } catch (IOException e) {
                // No operations.
            }
        }
    }

    public void printJson(String... parameters) {
        if (parameters.length % 2 != 0) {
            throw new IllegalArgumentException("parameters.length() should be even.");
        }

        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < parameters.length; i += 2) {
            map.put(parameters[i], parameters[i + 1]);
        }

        printJson(map);
    }
}
